package cn.kiliter.serviece;

import cn.kiliter.dao.UserDao;
import cn.kiliter.excation.UserException;
import cn.kiliter.model.User;
import cn.kiliter.utils.MailUtils;

import java.sql.SQLException;

public class UserService {
    private UserDao userDao = new UserDao();

    public void register(User user) throws UserException {
        try {
           userDao.addUser(user);
            String link = "http://localhost:8080/active?activeCode=" + user.getActiveCode();
            String html = "<a href=\"" + link + "\">欢迎你注册网上书城帐号,请点击激活</a>";
            //发送激活邮件
            MailUtils.sendMail(user.getEmail(),html,"queren");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new UserException("注册失败，用户名重复");
        }
    }
    public  void activeUser(String  activecode) throws UserException {
        User user=null;
        try {
             user = userDao.findUserByactiveCode(activecode);
             if(user==null){
                 throw new UserException("非法激活，用户不存在");
             }
             if(user!=null&&user.getState()==1){
                 throw new UserException("已激活");
             }
             userDao.updateState(activecode);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new UserException("激活失败");
        }
    }


    public User login(User login) throws UserException {
        try {
            User user=userDao.findUserByUserAndPassword(login);
            if(user==null){
                throw new UserException("用户名或密码错误");
            }
            if(user.getState()==0){
                throw  new UserException("用户未激活");
            }
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new UserException("登录失败");
        }
    }

    public User findById(int i) throws UserException {
        try {
            User user=userDao.findById(i);
            if(user==null){
                throw new UserException("username is empty");
            }
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new UserException("wrong");
        }

    }

    public void updateByUser(User user) throws UserException {
        try {
            userDao.updateByUser(user);
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new UserException("i do not know why");
        }
    }
}
